/**
 * Copyright &copy; 2016 CNJSON All rights reserved.
 */
package com.hongsuan.pplive.modules.live.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipaySubmit;
import com.cnjson.common.config.Global;
import com.cnjson.db.persistence.Page;
import com.cnjson.common.utils.DateUtils;
import com.cnjson.common.utils.IdGen;
import com.cnjson.common.utils.StringUtils;
import com.cnjson.common.web.BaseController;
import com.hongsuan.pplive.modules.live.entity.LivePresentRecord;
import com.hongsuan.pplive.modules.live.service.LivePresentRecordService;
import com.hongsuan.pplive.modules.sys.entity.User;
import com.hongsuan.pplive.modules.sys.service.SystemService;

/**
 * 单表生成Controller
 * 
 * @author cgli
 * @version 2016-04-18
 */
@Controller
@RequestMapping(value = "${adminPath}/live/livePresentRecord")
public class LivePresentRecordController extends BaseController {

	@Autowired
	private LivePresentRecordService livePresentRecordService;

	@Autowired
	private SystemService systemService;

	@ModelAttribute
	public LivePresentRecord get(@RequestParam(required = false) String id) {
		LivePresentRecord entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = livePresentRecordService.get(id);
		}
		if (entity == null) {
			entity = new LivePresentRecord();
		}
		return entity;
	}

	@RequiresPermissions("live:livePresentRecord:view")
	@RequestMapping(value = { "list", "" })
	public String list(LivePresentRecord livePresentRecord, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Page<LivePresentRecord> page = livePresentRecordService.findPage(new Page<LivePresentRecord>(request, response),
				livePresentRecord);
		model.addAttribute("page", page);
		String state = request.getParameter("state");
		if (state.equals("1")) {
			return "modules/live/livePresentApplyList";
		} else {
			return "modules/live/livePresentRecordList";
		}
	}

	@RequiresPermissions("live:livePresentRecord:edit")
	@RequestMapping(value = "applyAudit")
	// @ResponseBody
	public String applyAudit(@RequestParam("id") String id, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		// Map<String, Object> map = new HashMap<String, Object>();
		// map.put("status", Global.SUCCESS);
		String redirectUrl = "redirect:" + Global.getAdminPath() + "/live/livePresentRecord/list?state=1&repage";
		LivePresentRecord record = livePresentRecordService.get(id);
		String uri = request.getRequestURI();
		
		if (record != null) {
			Float money = record.getAmount();
			User user = systemService.getUser(record.getCreateById());
			if (user == null) {
				addMessage(redirectAttributes, "不存在的用户!");
				return redirectUrl;
			}
			// 金豆先结算为RMB!!!不直接转化金豆了！
		    //Float gmoney = (float) (user.getGold() / Global.moneyConvertor);
			Float total = user.getAccount() - money;
			if (total < 0) {
				addMessage(redirectAttributes, "余额不足不能提现!");
				return redirectUrl;
			}
			//user.setGold(0l);
			//user.setAccount(total);
			//systemService.updateUserAccount(user);

			// CALL API 同时要打折....
			Integer type = record.getType();
			
			// 真正打正用戶手上的钱
			float realMoney = money * Global.presentRate;

			// 微信转账支付
			if (type == 1) {
				weixinPay();
				
				// 支付宝
			} else if (type == 2) {
				alipay(uri,record.getAccount(), realMoney, user.getName());
			}
			addMessage(redirectAttributes, "提现放款审核成功");
		}
		return redirectUrl;
	}

	
	private void weixinPay() {
		// TODO Auto-generated method stub
		
	}

	private void alipay(String uri,String account, float money, String name) {
		
		// 服务器异步通知页面路径 需http://格式的完整路径，不允许加?id=123这类自定义参数
		String notify_url = uri + "alipay/notify_url";

		// 付款账号  必填
		// new  String(request.getParameter("WIDemail").getBytes("ISO-8859-1"),"UTF-8");
		String email = account;
		
		// new  String(request.getParameter("WIDaccount_name").getBytes("ISO-8859-1"),"UTF-8");
		// 付款账户名 必填，个人支付宝账号是真实姓名公司支付宝账号是公司名称
		String account_name = name;

		// new String(request.getParameter("WIDpay_date").getBytes("ISO-8859-1"),"UTF-8");
		// 付款当天日期  必填，格式：年[4位]月[2位]日[2位]，如：20100801
		String pay_date = DateUtils.formatDate(new Date(), "yyyyMMdd");

		// new  String(request.getParameter("WIDbatch_no").getBytes("ISO-8859-1"),"UTF-8");
		// 批次号 必填，格式：当天日期[8位]+序列号[3至16位]，如：201008010000001
		String batch_no = pay_date + IdGen.generateId(10); 

		// new String(request.getParameter("WIDbatch_fee").getBytes("ISO-8859-1"),"UTF-8");
		// 付款总金额 必填，即参数detail_data的值中所有金额的总和
		String batch_fee = String.valueOf(money); 
	 
		// new String(request.getParameter("WIDbatch_num").getBytes("ISO-8859-1"),"UTF-8");
		// 付款笔数 必填，即参数detail_data的值中，“|”字符出现的数量加1，最大支持1000笔（即“|”字符出现的数量999个）
		String batch_num = "1"; 
		
		// new String(request.getParameter("WIDdetail_data").getBytes("ISO-8859-1"),"UTF-8");
		// 付款详细数据 必填，格式：流水号1^收款方帐号1^真实姓名^付款金额1^备注说明1|流水号2^收款方帐号2^真实姓名^付款金额2^备注说明2....
		String detail_data = "";
		
		StringBuilder sb = new StringBuilder();
		sb.append(batch_no);
		sb.append("^");
		sb.append(email);
		sb.append("^");
		sb.append(account_name);
		sb.append("^");
		sb.append(money);
		sb.append("^");
		sb.append("转账");
		detail_data = sb.toString();

		// 把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", "batch_trans_notify");
		sParaTemp.put("partner", AlipayConfig.partner);
		sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("notify_url", notify_url);
		sParaTemp.put("email", email);
		sParaTemp.put("account_name", account_name);
		sParaTemp.put("pay_date", pay_date);
		sParaTemp.put("batch_no", batch_no);
		sParaTemp.put("batch_fee", batch_fee);
		sParaTemp.put("batch_num", batch_num);
		sParaTemp.put("detail_data", detail_data);
		// 建立请求
		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp, "get", "确认");
		System.out.println(sHtmlText);
	}

	@RequiresPermissions("live:livePresentRecord:view")
	@RequestMapping(value = "form")
	public String form(LivePresentRecord livePresentRecord, Model model) {
		model.addAttribute("livePresentRecord", livePresentRecord);
		return "modules/live/livePresentRecordForm";
	}

	@RequiresPermissions("live:livePresentRecord:edit")
	@RequestMapping(value = "save")
	public String save(LivePresentRecord livePresentRecord, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, livePresentRecord)) {
			return form(livePresentRecord, model);
		}
		livePresentRecordService.save(livePresentRecord);
		addMessage(redirectAttributes, "保存单表成功");
		return "redirect:" + Global.getAdminPath() + "/live/livePresentRecord/?repage";
	}

	@RequiresPermissions("live:livePresentRecord:edit")
	@RequestMapping(value = "delete")
	public String delete(LivePresentRecord livePresentRecord, RedirectAttributes redirectAttributes) {
		livePresentRecordService.delete(livePresentRecord);
		addMessage(redirectAttributes, "删除单表成功");
		return "redirect:" + Global.getAdminPath() + "/live/livePresentRecord/list?state=2&repage";
	}

}